<?php
namespace Addons\Docs\Controller;

use Home\Controller\AddonsController;

class ExportController extends AddonsController
{

    function lists()
    {
        $row = I('row', 10, 'intval');
        
        $lastid = I('lastid', 0, 'intval');
        if ($lastid > 0) {
            $map['file_id'] = array(
                'lt',
                $lastid
            );
        }
        
        $list = M('docs')->where($map)
            ->order('file_id desc')
            ->field('file_id,title,download_count,cTime')
            ->limit($row)
            ->select();
        
        foreach ($list as &$vo) {
            $vo['cTime'] = time_format($vo['cTime']);
        }
        
        // dump($list);
        $this->ajaxReturn($list);
    }

    function upload()
    {
        $return = array(
            'status' => 1,
            'msg' => '上传成功'
        );
        /* 调用文件上传组件上传文件 */
        $File = D('File');
        $file_driver = C('DOWNLOAD_UPLOAD_DRIVER');
        
        $info = $File->upload($_FILES, C('DOWNLOAD_UPLOAD'), C('DOWNLOAD_UPLOAD_DRIVER'), C("UPLOAD_{$file_driver}_CONFIG"));
        /* 记录附件信息 */
        if ($info) {
            // 记录到docs表里
            foreach ($info as $val) {
                $data['file_id'] = $val['id'];
                $data['title'] = $val['name'];
                $data['cTime'] = NOW_TIME;
                M('docs')->add($data);
            }
            $return['status'] = 1;
            $return = array_merge($info['download'], $return);
        } else {
            $return['status'] = 0;
            $return['info'] = $File->getError();
        }
        
        /* 返回JSON数据 */
        $this->ajaxReturn($return);
    }

    function download()
    {
        $return = array(
            'status' => 0,
            'msg' => '上传成功'
        );
        $id = $map['file_id'] = I('file_id');
        if (empty($id) || ! is_numeric($id)) {
            $return['msg'] = '参数出错';
            $this->ajaxReturn($return);
            exit();
        }
        
        M('docs')->where($map)->setInc('download_count', 1);
        
        $logic = D('Download', 'Logic');
        if (! $logic->download($id)) {
            $return['msg'] = $logic->getError();
            $this->ajaxReturn($return);
            exit();
        }
    }
}
